//用react封装
var currentpage = 1,totlepage = 1,i;//分页的当前页和总的页数
//表单数据：宝贝昵称、学生姓名、设备IMEI号、设备手机号、学校名称、班级名称、学籍号、性别、生日、身高、体重、
var tableData = [],schoolDataList = [],schoolDataAll = [];
//表单的最高高度、当前第几页、总页数、总行数
var otherData = {maxHeight:'0px',currentpage:0,totlepage:0,totlerows:0,pageLeft:0,pageRight:0};
//分页
var Page = React.createClass({
    setPage: function (e) {
        setPage($(e.target).html());
        this.props.onPageClick(1);
    },
    showPage: function () {
        showPage();
    },
    render: function () {
        {
            var items = [],
                svar = this;
            if(totlepage == 0 ){
                items.push({num:1,checked:true})
            }else if(totlepage < 6){
                for(i = 1;i <= totlepage ;i++) {
                    if (i == currentpage) {
                        items.push({num:i,checked:true})
                    } else {
                        items.push({num:i,checked:false})
                    }
                }
            }else if(currentpage >= (totlepage-2)) {//点在左边
                items.push({num:1,checked:false});
                items.push({num:'···',checked:false});
                for(i = totlepage-2;i <= totlepage ;i++){
                    if(i == currentpage){
                        items.push({num:i,checked:true})
                    }else{
                        items.push({num:i,checked:false})
                    }
                }
            }else if(currentpage <= 3){
                for(i = 1;i <= 3 ;i++) {
                    if (i == currentpage) {
                        items.push({num:i,checked:true})
                    } else {
                        items.push({num:i,checked:false})
                    }
                }
                items.push({num:'···',checked:false});
                items.push({num:totlepage,checked:false})
            }else {//点在两边
                items.push({num:1,checked:false});
                items.push({num:'···',checked:false});
                items.push({num:currentpage-1,checked:false});
                items.push({num:currentpage,checked:true});
                items.push({num:currentpage+1,checked:false});
                items.push({num:'···',checked:false});
                items.push({num:totlepage,checked:false})
            }
        }
        return (
            <div className="tableInfo-page">
                <div className="page-number">每页<span className="page-number-list" onClick={this.showPage}>{pagecount}</span>条</div>
                <div className="page-list" style={{top:pageListTop+"px"}}>
                    <ul>
                        {
                            pageList.map(function (item) {
                                return (<li onClick={svar.setPage}>{item}</li>)
                            })
                        }
                    </ul>
                </div>
                <div className="page-limit">
                    <ol className="page-limit-ol">
                        <li className="page-limit-img" name="-1" onClick={otherData.pageLeft == 0?'':svar.props.onPageClick.bind(svar,-1)}><span className={otherData.pageLeft == 0?'page-limit-left-no':'page-limit-left-yes'}/></li>
                        {
                            items.map(function (item) {
                                return (<li onClick={isNaN(item.num)?'':svar.props.onPageClick.bind(svar,item.num)}  className={item.checked == true?'page-limit-num page-limit-checked':'page-limit-num'} name={item.num}>{item.num}</li>)
                            })
                        }
                        <li className="page-limit-img" name="-2" onClick={otherData.pageRight == 0?'':svar.props.onPageClick.bind(svar,-2)}><span className={otherData.pageRight == 0?'page-limit-right-no':'page-limit-right-yes'}/></li>
                    </ol>
                </div>
            </div>
        );
    }
});
//表单组件
var Table = React.createClass({
    render: function () {
        return (
            <tr>
                <td style={{width: '5%'}}>{parseInt(this.props.listNumber)+1}</td>
                <td style={{width: '8%'}}>{this.props.queryresultObjectname}</td>
                <td style={{width: '8%'}}>{this.props.queryresultStudentname}</td>
                <td style={{width: '10%'}}>{this.props.queryresultMdtid}</td>
                <td style={{width: '9%'}}>{this.props.queryresultSimid}</td>
                <td style={{width: '14%'}}>{this.props.queryresultSchoolname}</td>
                <td style={{width: '10%'}}>{this.props.queryresultGrade}</td>
                <td style={{width: '9%'}}>{this.props.queryresultStudentid}</td>
                <td style={{width: '6%'}}>{this.props.queryresultSex}</td>
                <td style={{width: '9%'}}>{this.props.queryresultSbirthday}</td>
                <td style={{width: '6%'}}>{this.props.queryresultHeight}</td>
                <td style={{width: '6%'}}>{this.props.queryresultWeight}</td>
            </tr>
        );
    }
});
//父组件
var Main = React.createClass({
    //组件初始状态
    getInitialState: function () {
        return {
            otherData:this.props.otherData,
            tableData:this.props.tableData,
            schoolDataAll:this.props.schoolDataAll,
            schoolDataList:this.props.schoolDataList,
        }
    },
    componentDidMount: function () {
        //使用ajax取出数据然后组装数据列表
        // 然后使用this.setState();
        var height = $(document.body).height()+"px";
        var svar = this;
        suixun.ajax(serverUrl+'/studentInfoManage/queryStduentList.json?param={pagenumber:1,pagecount:"'+pagecount+'"}','',"get",function(data){
            if(data.code == 200){
                for(var i=0;i<data.info.queryresult.length;i++){
                    var obj=data.info.queryresult[i];
                    tableData[i] = {keyid:i,queryresultObjectname:obj.objectname,queryresultStudentname:obj.studentname,queryresultMdtid:obj.mdtid,queryresultSimid:obj.simid,queryresultSchoolname:obj.schoolname,queryresultGrade:obj.grade,queryresultStudentid:obj.studentid,queryresultSex:obj.sex,queryresultSbirthday:obj.birthday=="无"?"无":obj.birthday.substr(0,10),queryresultHeight:obj.height=="无"?"":obj.height+"cm",queryresultWeight:obj.weight=="无"?"无":obj.weight+"KG"};
                }
                var pageRight = 0;
                if(data.info.totlepage > 1){
                    pageRight = 1
                }
                otherData = {maxHeight:height,pageLeft:0,pageRight:pageRight};
                currentpage = 1;totlepage = data.info.totlepage;//初始化的时候赋值：分页的当前页和总的页数
                svar.setState({tableData:tableData,otherData:otherData});
                svar.selectSchoolData();//查询所有学校
            }
        });
        //绑定回车时间
        $(document).keypress(function(e) {
            var eCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
            if (eCode == 13){
                if($(".enterEvent").is(":focus")){
                    svar.onClickQuery();
                }
            }
        });
    },
    //查询学校数据
    selectSchoolData: function () {
        suixun.showLoding();//显示加载中
        var svar = this;
        suixun.ajax(serverUrl+'/schoolManage/querySchool.json','',"get",function(data){
            suixun.hideLoding();//隐藏加载中
            if(data.code == 200 ){
                for(var i=0;i<data.info.length;i++){
                    var obj=data.info[i];
                    schoolDataList[i] = {key:i,id:obj.id,schoolname:obj.schoolname};
                }
                schoolDataAll = schoolDataList;
                svar.setState({schoolDataList:schoolDataList,schoolDataAll:schoolDataAll});
            }else{
                svar.setState({schoolDataList:schoolDataList,schoolDataAll:schoolDataAll});
            }
        });
    },
    onClickQuery: function () {
        suixun.showLoding();//显示加载中
        var queryType = $(".school-or-table").html(),queryKey = "schoolname";
        if(queryType == "学生"){
            queryKey = "studentname";
        }
        var param="param={";
        param = getJsonDataNotEmpty(param,""+queryKey+"",$(".queryVal").val());
        param = getJsonDataNotEmpty(param,"pagenumber","1");
        param = getJsonDataNotEmpty(param,"pagecount",pagecount+'');
        param += "}";
        var svar = this;
        suixun.ajax(serverUrl+'/studentInfoManage/queryStduentList.json',param,"get",function(data){
            tableData = [];
            suixun.hideLoding();//隐藏加载中
            if(data.code == 200){
                for(var i=0;i<data.info.queryresult.length;i++){
                    var obj=data.info.queryresult[i];
                    tableData[i] = {keyid:i,queryresultObjectname:obj.objectname,queryresultStudentname:obj.studentname,queryresultMdtid:obj.mdtid,queryresultSimid:obj.simid,queryresultSchoolname:obj.schoolname,queryresultGrade:obj.grade,queryresultStudentid:obj.studentid,queryresultSex:obj.sex,queryresultSbirthday:obj.birthday=="无"?"无":obj.birthday.substr(0,10),queryresultHeight:obj.height=="无"?"":obj.height+"cm",queryresultWeight:obj.weight=="无"?"无":obj.weight+"KG"};
                }
                var height = $(document.body).height()+"px";
                var pageRight = 0;
                if(data.info.totlepage > 1){
                    pageRight = 1
                }
                otherData = {maxHeight:height,pageLeft:0,pageRight:pageRight};
                currentpage = 1;totlepage = data.info.totlepage;//初始化的时候赋值：分页的当前页和总的页数
                svar.setState({tableData:tableData,otherData:otherData});
            }
        });
    },
    onPageClick: function (num) {
        //分页-调用ajac然后把数据查询出来:获取name的值
        //计算currentpage
        suixun.showLoding();//显示加载中
        var onPageLeft = 0,onPageRight = 1,svar = this;
        if(num > 0){
            currentpage = num;
        }else if(num == -1 && currentpage > 1){
            currentpage --;
        }else if(num == -2  && currentpage < totlepage){
            currentpage ++;
        }else{
            return;
        }
        //修改左右的按钮
        if((currentpage == totlepage && totlepage == 1)|| totlepage == 0){
            onPageLeft = 0;
            onPageRight = 0;
        }else if(currentpage == totlepage && totlepage > 1){
            onPageLeft = 1;
            onPageRight = 0;
        }else if(1 < currentpage && currentpage < totlepage){
            onPageLeft = 1;
            onPageRight = 1;
        }
        var queryType = $(".school-or-table").html(),queryKey = "schoolname";
        if(queryType == "学生"){
            queryKey = "studentname";
        }
        var param="param={";
        param = getJsonDataNotEmpty(param,""+queryKey+"",$(".queryVal").val());
        param = getJsonDataNotEmpty(param,"pagenumber",""+currentpage+"");
        param = getJsonDataNotEmpty(param,"pagecount",pagecount+'');
        param += "}";
        //执行ajax获取数据然后组装
        var height = $(document.body).height()+"px";
        suixun.ajax(serverUrl+'/studentInfoManage/queryStduentList.json',param,"get",function(data){
            tableData = [];
            suixun.hideLoding();//隐藏加载中
            if(data.code == 200){
                for(var i=0;i<data.info.queryresult.length;i++){
                    var obj=data.info.queryresult[i];
                    tableData[i] = {keyid:i,queryresultObjectname:obj.objectname,queryresultStudentname:obj.studentname,queryresultMdtid:obj.mdtid,queryresultSimid:obj.simid,queryresultSchoolname:obj.schoolname,queryresultGrade:obj.grade,queryresultStudentid:obj.studentid,queryresultSex:obj.sex,queryresultSbirthday:obj.birthday=="无"?"无":obj.birthday.substr(0,10),queryresultHeight:obj.height=="无"?"":obj.height+"cm",queryresultWeight:obj.weight=="无"?"无":obj.weight+"KG"};
                }
                if(data.info.totlepage > 1 && data.info.totlepage > currentpage){
                    onPageRight = 1
                }else{
                    onPageRight = 0;
                }
                otherData = {maxHeight:height,totlerows:400,pageLeft:onPageLeft,pageRight:onPageRight};
                totlepage = data.info.totlepage;//初始化的时候赋值：分页的当前页和总的页数
                svar.setState({tableData:tableData,otherData:otherData});
            }
        });
    },
    /**
     * 改变弹出层学校输入框
     * @param e
     */
    onChangSchoolInput: function (e) {
        if($(".school-or-parent").html() == "学生"){
            return;
        }
        var val = $(e.target).val();
        if(val != ""){
            this.schoolArray(val,$(e.target).attr("data-list"));
        }else{
            $("."+$(e.target).attr("data-list")+"").hide();
        }
    },
    /**
     * 排序
     * @param val
     * @param cls
     */
    schoolArray: function (val,cls) {
        schoolDataList = [];
        for(var i = 0;i < schoolDataAll.length;i++){
            if((schoolDataAll[i].schoolname).indexOf(val) >= 0){
                schoolDataList.push({schoolname:schoolDataAll[i].schoolname});
            }
        }
        if(schoolDataList.length == 0){
            $("."+cls+"").hide();
        }else{
            $("."+cls+"").show();
            this.setState({schoolDataList:schoolDataList});
        }
    },
    /**
     * 点击学校输入框
     * @param e
     */
    onClickSchool: function (e) {
        if($(".school-or-parent").html() == "学生"){
            return;
        }
        this.schoolArray($(e.target).val(),$(e.target).attr("data-list"));
    },
    /**
     *点击学校
     */
    onClickBar: function (e) {
        $("#query_school").val($(e.target).html());
        this.onClickQuery();
    },
    render: function () {
        {
            var svar = this;
            var Tabels = this.state.tableData.map(function (data,index) {
                return (
                    <Table key={data.keyid} listNumber={index} queryresultObjectname={data.queryresultObjectname} queryresultStudentname={data.queryresultStudentname} queryresultMdtid={data.queryresultMdtid} queryresultSimid={data.queryresultSimid} queryresultSchoolname={data.queryresultSchoolname} queryresultGrade={data.queryresultGrade} queryresultStudentid={data.queryresultStudentid} queryresultSex={data.queryresultSex} queryresultSbirthday={data.queryresultSbirthday} queryresultHeight={data.queryresultHeight} queryresultWeight={data.queryresultWeight} />
                )
            })
        }
        return (
            <div className="tableManage-body">
                <header>
                    <div className="header-left">
                        <div className="header-left-studentInfo">
                            <a href="../parentInfoManage/queryParentList.html" className="header-left-button ">家长管理</a>
                            <a href="../teacherManage/classTeacher.html" className="header-left-button" style={{left:"10px"}}>教师管理</a>
                            <a href="../studentInfoManage/queryStduentList.html"  className="header-left-button showOrder" style={{left:"20px"}}>学生管理</a>
                        </div>
                        <div className="header-left-annotationsInfo">
                            <img src="../img/icon/annotations.png" />
                            <span className="header-left-annotations-arrowsLeft"/>
                            <div className="header-left-annotations">这里是注释。</div>
                        </div>
                    </div>
                    <div className="header-right">
                        <div className="header-right-select droup-select" style={{borderRadius:"5px 0 0 5px"}}>
                            <div className="school-or-table school-or-parent">学校</div>
                            <span className="lower-right-corner"/>
                            <div className="drop-down" >
                                <span className="select-value school-name" >学校</span>
                                <span className="select-value student-name" >学生</span>
                            </div>
                        </div>
                        <div className="header-right-query">
                            <div className="header-right-query-input">
                                <input className="queryVal enterEvent" type="text" onChange={this.onChangSchoolInput} onClick={this.onClickSchool}  id="query_school" data-list="querySchoolHistogram" maxLength="50" placeholder="请输入学校搜索"/>
                            </div>
                            <div className="header-right-query-img" maxLength="20" onClick={this.onClickQuery}></div>
                            <div className="schoolList querySchoolHistogram" data-inputId="query_school">
                                {
                                    schoolDataList.map(function (data) {
                                        return (
                                            <span className="schoolList-value" onClick={svar.onClickBar}>{data.schoolname}</span>
                                        )
                                    })
                                }
                            </div>
                        </div>
                    </div>
                </header>
                <div className="tableInfo">
                    <div className="tableInfo-data">
                        <div className="tableInfo-data-table" >
                            <table className="head-body">
                                <thead>
                                    <th style={{width: '5%'}}>序号</th>
                                    <th style={{width: '8%'}}>宝贝昵称</th>
                                    <th style={{width: '8%'}}>姓名</th>
                                    <th style={{width: '10%'}}>设备IMEI号</th>
                                    <th style={{width: '9%'}}>设备手机号</th>
                                    <th style={{width: '14%'}}>学校</th>
                                    <th style={{width: '10%'}}>班级</th>
                                    <th style={{width: '9%'}}>学籍号</th>
                                    <th style={{width: '6%'}}>姓别</th>
                                    <th style={{width: '9%'}}>生日</th>
                                    <th style={{width: '6%'}}>身高</th>
                                    <th style={{width: '6%'}}>体重</th>
                                </thead>
                                <tbody>
                                    {this.state.tableData==""?'':Tabels}
                                </tbody>
                            </table>
                            {this.state.tableData==""?<div className="tableNoData">{tableNoDataCount}</div>:''}
                        </div>
                    </div>

                    <Page maxHeight={this.state.maxHeight} pageLeft={this.state.pageLeft} onPageRight={this.state.onPageRight} currentpage={this.state.currentpage} totlepage={this.state.totlepage} totlerows={this.state.totlerows} onPageClick={this.onPageClick} />
                </div>
                <footer id="copyright">
                    <span><img src="../img/icon/copyright.png"/>{copyright}</span>
                </footer>
            </div>
        );
    }
});
ReactDOM.render(
    <Main  otherData={otherData} tableData={tableData} schoolDataAll={schoolDataAll} schoolDataList={schoolDataList} />,
    document.getElementById('tableManage')
);
//点击下拉框
$(".header-right-select").click(function () {
    var dropDown = $(this).find('.drop-down');
    if(dropDown.is(":hidden")){
        dropDown.slideDown();
    }else{
        dropDown.slideUp();
    }
});
//鼠标移动函数 —— 下拉选择学校、姓名
// $('.header-right .school-or-table').hover(function(){
//         if($(".drop-down").is(":hidden")){
//             $(this).parent().find('.drop-down').slideDown();
//             $(this).parent().hover(function(){},
//                 function(){
//                     $(this).parent().find(".drop-down").slideUp();
//                 }
//             );
//         }
//     },function(){}
// );
//选择学校、姓名
$('.drop-down>span').click(function() {
    $(".queryVal").attr("placeholder","请输入"+$(this).html()+"搜索");
    if($(this).html()=="学生" && $(".school-or-table").html() != "学生"){
        $("#query_school").val("");
    }else if($(this).html()=="学校" && $(".school-or-table").html() != "学校"){
        $("#query_school").val("");
    }
    $(".school-or-table").html($(this).html());
    $('.drop-down').slideUp();
});
function placeholderSupport() {
    return 'placeholder' in document.createElement('input');
}
$(function(){
    if(!placeholderSupport()){   // 判断浏览器是否支持 placeholder
        $('[placeholder]').focus(function() {
            var input = $(this);
            if (input.val() == input.attr('placeholder')) {
                input.val('');
                input.removeClass('placeholder');
            }
        }).blur(function() {
            var input = $(this);
            if (input.val() == '' || input.val() == input.attr('placeholder')) {
                input.addClass('placeholder');
                input.val(input.attr('placeholder'));
            }
        }).blur();
    }
});
//学校下拉列表
$("*").bind("click",function(e){
    var target = $(e.target);
    if(target.closest(".schoolList-value").length == 1){
        $("#"+$(target.parent()).attr("data-inputId")+"").val(target.html());
        $(".schoolList").hide();
    }else{
        $(".schoolList").hide();
    }
});